package com.azxc.rapid.auth.granter;

import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONObject;
import com.azxc.rapid.auth.constant.AuthConstant;
import com.azxc.rapid.auth.service.RapidUserDetails;
import com.azxc.rapid.auth.utils.TokenUtil;
import com.azxc.rapid.core.redis.cache.RapidRedis;
import com.azxc.rapid.core.tool.api.R;
import com.azxc.rapid.core.tool.support.Kv;
import com.azxc.rapid.core.tool.utils.Func;
import com.azxc.rapid.core.tool.utils.StringUtil;
import com.azxc.rapid.core.tool.utils.WebUtil;
import com.azxc.rapid.system.user.entity.User;
import com.azxc.rapid.system.user.entity.UserInfo;
import com.azxc.rapid.system.user.enums.UserEnum;
import com.azxc.rapid.system.user.feign.IUserClient;
import org.springframework.security.authentication.AbstractAuthenticationToken;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.oauth2.common.exceptions.InvalidGrantException;
import org.springframework.security.oauth2.provider.*;
import org.springframework.security.oauth2.provider.token.AbstractTokenGranter;
import org.springframework.security.oauth2.provider.token.AuthorizationServerTokenServices;

import javax.servlet.http.HttpServletRequest;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * @author linym
 * @className: WestoneGranter
 * @description:
 * @date 2023/1/16 10:05
 * @version：1.0
 */
public class ShowGranter extends AbstractTokenGranter {
	private static final String GRANT_TYPE = "show";
	private final IUserClient userClient;




	private RapidRedis rapidRedis;



	protected ShowGranter(AuthorizationServerTokenServices tokenServices, ClientDetailsService clientDetailsService, OAuth2RequestFactory requestFactory, IUserClient userClient) {
		super(tokenServices, clientDetailsService, requestFactory, GRANT_TYPE);
		this.userClient = userClient;

	}



	@Override
	protected OAuth2Authentication getOAuth2Authentication(ClientDetails client, TokenRequest tokenRequest) {
		HttpServletRequest request = WebUtil.getRequest();


		Map<String, String> parameters = new LinkedHashMap<>(tokenRequest.getRequestParameters());
		String account = parameters.get("account");
		if(StringUtil.isEmpty(account)){
			throw new InvalidGrantException("缺少参数account！");

		}
		String tenantId = Func.toStr(request.getHeader(TokenUtil.TENANT_HEADER_KEY), TokenUtil.DEFAULT_TENANT_ID);

		RapidUserDetails rapidUserDetails;


		// 远程调用，获取认证信息
		R<UserInfo> result = userClient.userInfo(tenantId,account);

		if (result.isSuccess()) {
			User user = result.getData().getUser();
			Kv detail = result.getData().getDetail();
			if (user == null) {
				throw new InvalidGrantException("演示授权登录失败，未找到该用户");
			}
			rapidUserDetails = new RapidUserDetails(user.getId(),
				tenantId, result.getData().getOauthId(), user.getName(), user.getRealName(), user.getDeptId(), user.getPostId(), user.getRoleId(), Func.join(result.getData().getRoles()),null,
				user.getName(), AuthConstant.ENCRYPT + user.getPassword(), detail, true, true, true, true,
				AuthorityUtils.commaSeparatedStringToAuthorityList(Func.join(result.getData().getRoles())));
		} else {
			throw new InvalidGrantException("演示 grant failure, feign client return error");
		}


		Authentication userAuth = new UsernamePasswordAuthenticationToken(rapidUserDetails, null, rapidUserDetails.getAuthorities());
		((AbstractAuthenticationToken) userAuth).setDetails(parameters);
		OAuth2Request storedOAuth2Request = getRequestFactory().createOAuth2Request(client, tokenRequest);

		// 返回 OAuth2Authentication
		return new OAuth2Authentication(storedOAuth2Request, userAuth);
	}


}
